#!/usr/bin/env python

import wsgiref.handlers
import urlparse, logging
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from google.appengine.api.labs import taskqueue
from schema import Document, key_name_from_url

class MainHandler(webapp.RequestHandler):
  def get(self):
    user = users.get_current_user()
    if user:
      if users.is_current_user_admin():
        body = '<form method="POST"><input name="url" /></form>'
        self.response.out.write("<html><body>%s</body></html>" % body)
      else:
        self.redirect(users.create_logout_url("/"))
    else:
      self.redirect(users.create_login_url("/"))

  def post(self):
    # Create a document for the URL
    url = urlparse.urlparse(self.request.get('url')).geturl()
    key_name = key_name_from_url(url)
    document = Document.get_by_key_name(key_name)
    if document is None:
      logging.debug("I've never seen that URL, so I'll make a new document.")
      document = Document(key_name=key_name, url=url)
      document.put()

    # Start fetching
    logging.debug("Now I'll make a task to figure out what to fetch.")
    task = taskqueue.Task(
      url='/find-documents-to-fetch',
    )
    task.add(queue_name='fetch')

    self.redirect("/")

def main():
  logging.getLogger().setLevel(logging.DEBUG)
  wsgiref.handlers.CGIHandler().run(webapp.WSGIApplication([
    ('/', MainHandler),
  ]))

if __name__ == '__main__':
  main()
